package com.zhentao.controller;

import com.zhentao.pojo.UserCollection;
import com.zhentao.pojo.Content;
import com.zhentao.pojo.Product;
import com.zhentao.service.ContentService;
import com.zhentao.service.ProductService;
import com.zhentao.service.UserCollectionService;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author gyz
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserCollectionService userCollectionService;
    @Autowired
    ProductService productService;
    @Autowired
    ContentService contentService;
    //添加收藏
    //http://localhost:8081/user/CollAdd
    @RequestMapping("CollAdd")
    public Object getCollAdd(@RequestBody UserCollection userCollection){
        try {
            // 检查是否已经收藏过
            boolean exists = userCollectionService.count(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCollection>()
                    .eq("user_id", userCollection.getUserId())
                    .eq("entity_type", userCollection.getEntityType())
                    .eq("entity_id", userCollection.getEntityId())
            ) > 0;
            
            if (exists) {
                return "已经收藏过了";
            }
            
            // 设置收藏时间
            if (userCollection.getCollectTime() == null) {
                userCollection.setCollectTime(new java.util.Date());
            }
            
            boolean saved = userCollectionService.save(userCollection);
            return saved ? "收藏成功" : "收藏失败";
        } catch (Exception e) {
            return "收藏失败：" + e.getMessage();
        }
    }
    //登录用户所有收藏展示
    @RequestMapping("CollAll")
    public Object getCollAll(Long userid){
        try {
            // 直接查询该用户的收藏记录
            List<UserCollection> list = userCollectionService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCollection>()
                    .eq("user_id", userid)
                    .orderByDesc("collect_time")
            );
            
            List<Map<String, Object>> resultList = new ArrayList<>();
            
            for (UserCollection userCollection : list) {
                Map<String, Object> collectionData = new HashMap<>();
                collectionData.put("id", userCollection.getId());
                collectionData.put("userId", userCollection.getUserId());
                collectionData.put("entityType", userCollection.getEntityType());
                collectionData.put("entityId", userCollection.getEntityId());
                collectionData.put("collectTime", userCollection.getCollectTime());
                
                if("product".equals(userCollection.getEntityType())){
                    // 获取商品信息
                    Product product = productService.getById(userCollection.getEntityId());
                    if(product != null){
                        Map<String, Object> productData = new HashMap<>();
                        productData.put("id", product.getId());
                        productData.put("name", product.getName());
                        productData.put("intro", product.getIntro());
                        productData.put("cover", product.getCover());
                        productData.put("price", product.getPrice());
                        collectionData.put("product", productData);
                        resultList.add(collectionData);
                    }
                } else if("content".equals(userCollection.getEntityType())){
                    // 获取内容信息（课程）
                    Content content = contentService.getById(userCollection.getEntityId());
                    if(content != null){
                        Map<String, Object> contentData = new HashMap<>();
                        contentData.put("id", content.getId());
                        contentData.put("title", content.getTitle());
                        contentData.put("intro", content.getIntro());
                        contentData.put("cover", content.getCover());
                        contentData.put("price", content.getPrice());
                        collectionData.put("content", contentData);
                        resultList.add(collectionData);
                    }
                }
            }
            return resultList;
        } catch (Exception e) {
            return "获取收藏列表失败：" + e.getMessage();
        }
    }

    // 删除收藏
    @RequestMapping("CollRemove")
    public Object removeCollection(@RequestBody UserCollection userCollection){
        try {
            // 根据用户ID、实体类型和实体ID删除收藏
            boolean removed = userCollectionService.remove(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCollection>()
                    .eq("user_id", userCollection.getUserId())
                    .eq("entity_type", userCollection.getEntityType())
                    .eq("entity_id", userCollection.getEntityId())
            );
            return removed ? "删除成功" : "删除失败";
        } catch (Exception e) {
            return "删除失败：" + e.getMessage();
        }
    }

    // 批量删除收藏
    @RequestMapping("CollBatchRemove")
    public Object batchRemoveCollections(@RequestBody List<UserCollection> collections){
        try {
            int successCount = 0;
            int failCount = 0;
            
            for (UserCollection collection : collections) {
                boolean removed = userCollectionService.remove(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCollection>()
                        .eq("user_id", collection.getUserId())
                        .eq("entity_type", collection.getEntityType())
                        .eq("entity_id", collection.getEntityId())
                );
                if (removed) {
                    successCount++;
                } else {
                    failCount++;
                }
            }
            
            return String.format("批量删除完成，成功：%d个，失败：%d个", successCount, failCount);
        } catch (Exception e) {
            return "批量删除失败：" + e.getMessage();
        }
    }

}
